package tech.dongling.boot.common.parser;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import tech.dongling.boot.ioc.LightIocContainer;

import java.util.List;
import java.util.Properties;

public class ProtocolServerInitializer extends ByteToMessageDecoder {
    private final LightIocContainer ioc;
    private final Properties config;

    public ProtocolServerInitializer(LightIocContainer ioc, Properties config) {
        this.ioc = ioc;
        this.config = config;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        if (in.readableBytes() < 1) return;

        in.markReaderIndex();
        in.resetReaderIndex();
        ChannelPipeline pipeline = ctx.pipeline();
        pipeline.remove(this);

        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new HttpObjectAggregator(1024 * 10));
        pipeline.addLast(new HttpProtocolHandler(ioc, config));
    }
}